package io.noties.markwon.base.html.tag

import android.text.TextUtils
import io.noties.markwon.base.MarkwonConfiguration
import io.noties.markwon.base.RenderProps
import io.noties.markwon.base.html.CssInlineStyleParser
import io.noties.markwon.base.html.HtmlTag
import io.noties.markwon.base.image.ImageProps
import io.noties.markwon.base.html.video.Video
import io.noties.markwon.base.html.video.VideoProps
import timber.log.Timber

class VideoHandler( imageSizeParser : SizeParser = SizeParserImpl(CssInlineStyleParser.create()))  : AbstractRectSizeTagHandler(imageSizeParser) {

    override fun supportedTags(): List<String> {
        return listOf("video","audio")
    }

    override fun getSpans(
        configuration: MarkwonConfiguration,
        renderProps: RenderProps,
        tag: HtmlTag
    ): Any? {
        val attributes = tag.attributes()
        val src = attributes["src"]
        Timber.d("VideoHandler video getSpans start.src=$src")
        if (TextUtils.isEmpty(src)) {
            return null
        }

        var poster = attributes["poster"]

        val spanFactory = configuration.spansFactory().get(
            Video::class.java
        ) ?: return null

        poster = if (TextUtils.isEmpty(poster))
                     "drawable://placeholder_image_article_day"
                 else
                     configuration.imageDestinationProcessor().process(poster!!)

        // todo: replacement text is link... as we are not at block level
        // and cannot inspect the parent of this node... (img and a are both inlines)
        //
        // but we can look and see if we are inside a LinkSpan (will have to extend TagHandler
        // to obtain an instance SpannableBuilder for inspection)
        ImageProps.DESTINATION[renderProps] = poster

        val sizeParsed=sizeParser(configuration, renderProps, tag)

        ImageProps.REPLACEMENT_TEXT_IS_LINK[renderProps] = false
        VideoProps.VIDEO_DESTINATION[renderProps] = configuration.imageDestinationProcessor().process(src!!)

        val span=spanFactory.getSpans(configuration, renderProps)
        Timber.d("VideoHandler video getSpans span=$span end.src=$src\tposter=$poster\t size=$sizeParsed,tag start=${tag.start()}  end=${tag.end()}")
        return span
    }
}